using System;
using System.Linq;
using System.Reflection;
using Common.Tests;

namespace Common.Tests
{
	public static class TestObjectGenerator
	{
		public static object CreateRandomEntity(Type type, bool recursively)
		{
			object result = Activator.CreateInstance(type);

			PropertyInfo[] properties = type.GetProperties();

			foreach (PropertyInfo property in properties.Where(prop => prop.CanWrite))
			{
				Type propertyType = property.PropertyType;
				
				if(propertyType.IsEnum)
				{
					continue;
				}
				
				object propertyValue = null;

				if(propertyType == typeof(string))
				{
					propertyValue = TestHelper.RandomString;
				}

				if(propertyType == typeof(int))
				{
					propertyValue = TestHelper.Random.Next();
				}

				if(propertyType == typeof(decimal))
				{
					propertyValue = new Decimal(TestHelper.Random.NextDouble());
				}

				if(propertyType == typeof(DateTime))
				{
					propertyValue = TestHelper.RandomDateTime;
				}

				if(propertyValue == null && recursively)
				{
					try
					{
						propertyValue = CreateRandomEntity(propertyType, true);
					}
					catch
					{
						// do nothing...
					}
				}

				if (propertyValue != null)
				{
					property.SetValue(result, propertyValue, null);
				}
			}

			return result;
		}

		public static T CreateRandomEntity<T>(bool recursively) where T : new()
		{
			return (T) CreateRandomEntity(typeof (T), recursively);
		}

		public static T CreateRandomEntity<T>() where T : new()
		{
			return (T)CreateRandomEntity(typeof(T), false);
		}
	}
}